package com.mxx.basic.server.retrofit.observer;

import android.app.Activity;

import androidx.appcompat.app.AppCompatActivity;
import com.mxx.basic.utils.ToastUtils;
import com.yp.loading.widget.LoadingDialog;

import java.io.IOException;

import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import okhttp3.ResponseBody;
import retrofit2.Response;

public abstract class StringObserver extends BaseObserver<Response<ResponseBody>> {
    private LoadingDialog mDialog;
    protected boolean isShowLoading;
    protected boolean isShowToast;

    public StringObserver(Activity mActivity) {
        super((AppCompatActivity) mActivity);
    }

    public StringObserver(boolean isShowLoading, Activity mActivity) {
        super((AppCompatActivity) mActivity);
        if (isShowLoading) {
            mDialog = new LoadingDialog();
        }
    }

    @Override
    public void onSubscribe(@NonNull Disposable d) {
        super.onSubscribe(d);
       if (mDialog!=null){
           mDialog = new LoadingDialog();
           mDialog.show(mActivity.getSupportFragmentManager(), "LoadingDialog");
       }
    }

    @Override
    public void onNext(Response<ResponseBody> response) {
        mLogger.json("原始未包装的数据：" + response.toString());
        if (response.isSuccessful()) {
            if (response.code() == 200) {
                ResponseBody body = response.body();
                if (body == null) {
                    onFailed(true, response.code(), "数据为空");
                    return;
                }
                String json = null;
                try {
                    json = body.string().trim();
                } catch (IOException e) {
                    e.printStackTrace();
                    onFailed(true, response.code(), "解析异常");
                }
                onSuccess(json);
            }
        } else {
            okhttp3.Response raw = response.raw();
            onFailed(false, response.code(), raw.message());
        }
    }

    @Override
    public void onComplete() {
        super.onComplete();
        dialogDismiss();
    }

    private void dialogDismiss() {
        if (mDialog == null) {
            return;
        }
        mDialog.dismiss();
    }

    @Override
    public void onError(Throwable t) {
        super.onError(t);
        dialogDismiss();
    }

    protected abstract void onSuccess(String originalJson);

    protected void onFailed(int code, String msg) {
//        ToastUtils.showToast(mActivity,msg);
//        logOrShowMsg(msg);
    }

    protected void onFailed(boolean showToast, int code, String msg) {
        ToastUtils.showToast(mActivity, msg);
    }
}
